#include "mywebtabmgr.h"


MyWebTabMgr::MyWebTabMgr(QObject *parent) : QObject(parent)
{

}

void MyWebTabMgr::Init(MainDlg *pMain)
{
    m_pMainDlg = pMain;
    connect(m_pMainDlg->ui->view_tab, SIGNAL(tabCloseRequested(int)), this, SLOT(tabCloseRequested(int)));
    connect(this, SIGNAL(sig_notify_msg(QString)), m_pMainDlg->ui->status_lab, SLOT(setText(QString)));
    connect(this, SIGNAL(sig_url_msg(QString)), m_pMainDlg->ui->nav_edit_addr, SLOT(setText(QString)));
    connect(m_pMainDlg->ui->view_tab, SIGNAL(currentChanged(int)), this, SLOT(currentChanged(int)));
    m_pDownLoadSDK = new MyDownLoadSDK(this);
    m_pDownLoadSDK->Init();
}

MyWebView *MyWebTabMgr::CreateTab(QWebEngineProfile *profile, bool bActive)
{
    // 清除背景
    m_pMainDlg->ui->view_tab->setStyleSheet("");
    // 添加Tab
    auto oneWebTab = new MyWebTab(m_pMainDlg->m_pWebTabMgr, profile);
    int nIndex = oneWebTab->getTabIndex();
    if(bActive){
        m_pMainDlg->ui->view_tab->setCurrentIndex(nIndex);
    }
    return oneWebTab->getWebView();
}

void MyWebTabMgr::tabCloseRequested(int nIndex)
{
    qDebug()<<"MyWebTabMgr::tabCloseRequested:"<<nIndex;
    m_pMainDlg->ui->view_tab->widget(nIndex)->deleteLater();
    m_pMainDlg->ui->view_tab->removeTab(nIndex);
    QString strCSS = "background-image: url(:/bg.png);background-repeat: no-repeat;background-position:center center;";
    if( m_pMainDlg->ui->view_tab->count() == 0 ){
        m_pMainDlg->ui->view_tab->setStyleSheet(strCSS);
    }
}

void MyWebTabMgr::currentChanged(int nIndex)
{
    /*
    WebView *view = webView(index);
    if (!view->url().isEmpty())
        view->setFocus();
    emit titleChanged(view->title());
    emit loadProgress(view->loadProgress());
    emit urlChanged(view->url());
    emit favIconChanged(view->favIcon());
    emit webActionEnabledChanged(QWebEnginePage::Back, view->isWebActionEnabled(QWebEnginePage::Back));
    emit webActionEnabledChanged(QWebEnginePage::Forward, view->isWebActionEnabled(QWebEnginePage::Forward));
    emit webActionEnabledChanged(QWebEnginePage::Stop, view->isWebActionEnabled(QWebEnginePage::Stop));
    emit webActionEnabledChanged(QWebEnginePage::Reload,view->isWebActionEnabled(QWebEnginePage::Reload));

    */
    qDebug()<<"currentChanged"<<nIndex;
    if( nIndex >= 0 ){
        MyWebTab* pTab = (MyWebTab*)m_pMainDlg->ui->view_tab->currentWidget();
        QWebEnginePage* pPage = pTab->getWebView()->page();
        m_pMainDlg->ui->nav_edit_addr->setText(pPage->url().toString());
        m_pMainDlg->ui->nav_btn_left->setEnabled(pPage->action(QWebEnginePage::Back)->isEnabled());
        m_pMainDlg->ui->nav_btn_right->setEnabled(pPage->action(QWebEnginePage::Forward)->isEnabled());
    }
}
